﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Reactive.Linq;
using System.Xml;
using System.Xml.Serialization;

namespace Wulong.Phone.Utils.Xml
{
    /// <summary>
    /// 
    /// </summary>
    public static class XmlMapper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="reader"></param>
        /// <param name="xmlRoot"></param>
        /// <returns></returns>
        public static IEnumerable<T> GetItem<T>(XmlReader reader, string xmlRoot) where T : class
        {
            var serializer = new XmlSerializer(typeof(T));
            while (reader.GoToElement(xmlRoot))
            {
                yield return serializer.Deserialize(reader) as T;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="uri"></param>
        /// <param name="xmlRoot"></param>
        /// <returns></returns>
        public static IObservable<T> GetObservableItems<T>(Uri uri, string xmlRoot) where T : class
        {
            return
                (from request in Observable.Return((HttpWebRequest)WebRequest.Create(uri))
                 from response in Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse)()
                 from item in GetItem<T>(XmlReader.Create(response.GetResponseStream()), xmlRoot).ToObservable()
                 select item).ObserveOnDispatcher();
        }
    }
}
